//
// Created by Pulsar on 2021/1/8.
//

#include <hkvqcore/driver/local_cam_driver.h>
#include <exception>
#include <utility>

namespace hkvqcore {
    namespace driver {
        Capture::Capture() = default;

        Capture::Capture(int index) {
            this->index = index;
            IS_FILE = false;
        }

        long Capture::Init() {
            this->cap = new cv::VideoCapture();
            try {
                if (IS_FILE) {
                    cap->open(this->video_file);
                } else {
                    cap->open(index);
                    std::cout << "LocalCam Open ON:" << std::endl;
                }
                if (!cap->isOpened()) {
                    throw std::exception("LocalCam Open Error");
                }
            } catch (cv::Exception &e) {
                std::cout << e.what() << std::endl;
                return -2;
            } catch (std::exception &e) {
                std::cout << e.what() << std::endl;
                return -2;
            }
            return -1;
        }

        cv::Mat Capture::Read() {
            cv::Mat frame;
            *cap >> frame;
//            cv::imshow("frame",frame);
//            cv::waitKey(1);
            return frame;
        }

        void Capture::Release() {
            this->cap->release();
        }

        Capture::Capture(std::string video_file) : video_file(std::move(video_file)) {
            IS_FILE = true;
        }

        long Capture::Init(int index) {
            this->index = index;
            IS_FILE = false;
            this->cap = new cv::VideoCapture();
            try {
                cap->open(index);
                if (!cap->isOpened()) {
                    throw std::exception("LocalCam Open Error");
                }
            } catch (cv::Exception &e) {
                std::cout << e.what() << std::endl;
                return -2;
            } catch (std::exception &e) {
                std::cout << e.what() << std::endl;
                return -2;
            }
            return -1;
        }

        long Capture::Init(std::string video_file) {
            IS_FILE = true;
            this->video_file = video_file;
            this->cap = new cv::VideoCapture();
            try {
                cap->open(video_file);
                if (!cap->isOpened()) {
                    throw std::exception("WebCam Open Error");
                }
            } catch (cv::Exception &e) {
                std::cout << e.what() << std::endl;
                return -2;
            } catch (std::exception &e) {
                std::cout << e.what() << std::endl;
                return -2;
            }
            return -1;
        }
    }
}
